package models

import (
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"orderApi/express"
	"orderApi/express/debang"
	"orderApi/express/jingdong"
	"orderApi/express/shunfeng"
	"os"
	"sort"
	"xorm.io/core"
)

type Crm struct {
	Engine *xorm.Engine
	Err    error
}

var tbMappers core.PrefixMapper

func init() {
	_ = os.Setenv("NLS_LANG", "AMERICAN_AMERICA.AL32UTF8") // 修正中文乱码
}

const (
	driverName = "mysql"
	dBconnect  = "root:123456@tcp(192.168.0.12:3306)/expressage?charset=utf8"
)

// CrmDbCommit  建立mysql连接池
func (e *Crm) CrmDbCommit() error {

	e.Engine, e.Err = xorm.NewEngine(driverName, dBconnect)
	if e.Err != nil {
		return e.Err
	}
	// tbMappe := core.NewPrefixMapper(core.SnakeMapper{}, tbMapper)
	e.Engine.ShowSQL(true)
	e.Engine.SetTableMapper(tbMappers)
	return nil
}

// Close 关闭mysql连接池
func (e *Crm) Close() {
	e.Engine.Close()

}

func RoutesPost(p string) (rs express.BenXiRoutes) {

	// 序列化
	ps := new(express.Parameters)
	json.Unmarshal([]byte(p), ps)
	// 判断用户的参数
	// 顺丰快递
	if ps.Som == "shunfeng" {
		if ps.PartnerID == "" {
			rs.Status = false
			rs.Message = "PartnerID 客户编码为空！"
			return rs
		}
		if ps.AppSecret == "" {
			rs.Status = false
			rs.Message = "secret 合作伙伴密钥 为空！"
			return rs
		}
		if ps.Nu == "" {
			rs.Status = false
			rs.Message = "secret 合作伙伴密钥 为空！"
			return rs
		}
		rs = shunfeng.SfRoutesPost(ps.PartnerID, ps.AppSecret, ps.Nu)
		if !rs.Status {
			rs.Nu = ps.Nu
			rs.Som = ps.Som
			return rs
		}
		SortTheUpdate(&rs, ps.Som, ps.Sort)
		rs.Nu = ps.Nu
		rs.Som = ps.Som
		rs.Status = true
		rs.Message = "成功"
		return rs

		// 进行快递的状态统一更新

	} else if ps.Som == "jingdong" {
		// 京东快递
		if ps.AppKey == "" {
			rs.Status = false
			rs.Message = "应用的appKey 为空！"
			return rs
		}
		if ps.AppSecret == "" {
			rs.Status = false
			rs.Message = "secret合作伙伴密钥 为空！"
			return rs
		}
		if ps.AccessToken == "" {
			rs.Status = false
			rs.Message = "平台分配的access_toke 为空！"
			return rs
		}
		if ps.CustomerCode == "" {
			rs.Status = false
			rs.Message = "CustomerCode 商家编码/青龙业主号/配送编码/月结编码 为空！"
			return rs
		}
		if ps.Nu == "" {
			rs.Status = false
			rs.Message = "Nu 快递单号 为空！"
			return rs
		}

		var body []string
		body = make([]string, 3)
		body[0] = ps.CustomerCode
		body[1] = ps.Nu
		body[2] = "jd_12"
		str, _ := json.Marshal(body)
		rs = jingdong.JdRoutesPost(ps.AppKey, ps.AppSecret, ps.AccessToken, string(str))
		if !rs.Status {
			rs.Nu = ps.Nu
			rs.Som = ps.Som
			return rs
		}
		SortTheUpdate(&rs, ps.Som, ps.Sort)
		rs.Nu = ps.Nu
		rs.Som = ps.Som
		rs.Status = true
		rs.Message = "成功"
		return rs
	} else if ps.Som == "debang" {
		// 德邦快递
		if ps.AppKey == "" {
			rs.Status = false
			rs.Message = "应用的appKey 为空！"
			return rs
		}
		if ps.PartnerID == "" {
			rs.Status = false
			rs.Message = "PartnerID 客户编码为空！"
			return rs
		}
		if ps.Nu == "" {
			rs.Status = false
			rs.Message = "Nu 快递单号 为空！"
			return rs
		}
		rs = debang.DbRoutesPost(ps.AppKey, "{\"mailNo\":\""+ps.Nu+"\"}", ps.PartnerID)
		if !rs.Status {
			rs.Nu = ps.Nu
			rs.Som = ps.Som
			return rs
		}
		SortTheUpdate(&rs, ps.Som, ps.Sort)
		rs.Nu = ps.Nu
		rs.Som = ps.Som
		rs.Status = true
		rs.Message = "成功"
		return rs
	}

	rs.Nu = ps.Nu
	rs.Som = ps.Som
	rs.Status = false
	rs.Message = "查询快递 " + ps.Som + " 暂不支持！"

	return rs
}

// SortTheUpdate 进行 structs 排序 并进行code的统一替换
func SortTheUpdate(r *express.BenXiRoutes, som, sorts string) {

	if len(r.Routes) == 0 {
		r.Status = false
		r.Message = "快递路由为空！"
		return
	}

	// 进行 路由状态码统一的替换
	e := new(Crm)
	err := e.CrmDbCommit()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer e.Close()
	for k, v := range r.Routes {
		fmt.Println(v)
		if v.OpCode == "" {
			query, _ := e.Engine.Query("SELECT rs.state AS state,rs.op_code AS op_code FROM routing_status rs LEFT JOIN express_routing_status ers ON ers.routing_status_id = rs.id WHERE ers.som = ?  AND ers.op_name = ?", som, v.OpeTitle)
			if len(query) == 0 {
				r.Routes[k].OpCode = ""
				continue
			}
			r.Routes[k].OpCode = string(query[0]["op_code"])
			continue
		}
		query, _ := e.Engine.Query("SELECT rs.state AS state,rs.op_code AS op_code FROM routing_status rs LEFT JOIN express_routing_status ers ON ers.routing_status_id = rs.id WHERE ers.som = ?  AND ers.op_code = ?;", som, v.OpCode)
		if len(query) == 0 {
			r.Routes[k].OpCode = ""
			continue
		}
		r.Routes[k].OpCode = string(query[0]["op_code"])
	}

	// 进行排序 默认 desc
	if sorts == "asc" {
		sort.Slice(r.Routes, func(i, j int) bool { // asc
			return r.Routes[i].Time < r.Routes[j].Time
		})

		if r.Routes[len(r.Routes)-1].OpCode == "4" || r.Routes[len(r.Routes)-1].OpCode == "401" || r.Routes[len(r.Routes)-1].OpCode == "402" {
			r.State = "4"
			return
		}

		for _, v := range r.Routes {
			if v.OpCode == "6" || v.OpCode == "66" {
				if r.Routes[len(r.Routes)-1].OpCode == "3" || r.Routes[len(r.Routes)-1].OpCode == "301" || r.Routes[len(r.Routes)-1].OpCode == "302" || r.Routes[len(r.Routes)-1].OpCode == "303" || r.Routes[len(r.Routes)-1].OpCode == "304" {
					r.State = "4"
					return
				}
				r.State = "6"
				return
			}

		}

		query, _ := e.Engine.Query("SELECT state FROM routing_status WHERE op_code = ?;", r.Routes[len(r.Routes)-1].OpCode)
		if len(query) == 0 {
			r.State = "2"
			return
		}
		r.State = string(query[0]["state"])

	} else {
		sort.Slice(r.Routes, func(i, j int) bool { // desc
			return r.Routes[i].Time > r.Routes[j].Time
		})

		if r.Routes[0].OpCode == "4" || r.Routes[0].OpCode == "401" || r.Routes[0].OpCode == "402" {
			r.State = "4"
			return
		}

		for _, v := range r.Routes {
			if v.OpCode == "6" || v.OpCode == "66" {
				if r.Routes[0].OpCode == "3" || r.Routes[0].OpCode == "301" || r.Routes[0].OpCode == "302" || r.Routes[0].OpCode == "303" || r.Routes[0].OpCode == "304" {
					r.State = "4"
					return
				}
				r.State = "6"
				return
			}

		}

		query, _ := e.Engine.Query("SELECT state FROM routing_status WHERE op_code = ?;", r.Routes[0].OpCode)
		if len(query) == 0 {
			r.State = "2"
			return
		}
		r.State = string(query[0]["state"])
	}

}
